package cn.ijero.pictureselector.loader.image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;

import java.util.HashMap;

import cn.ijero.pictureselector.executor.ExecutorManager;
import cn.ijero.pictureselector.util.MimeTypeUtil;

public class ImageLoaderBuilder {

    private static final String TAG = "ImageLoaderBuilder";

    private static final LruCache<String, Bitmap> cachePool = new LruCache<>(100);
    private static final HashMap<String, ImageView> imageViewHashMap = new HashMap<>();

    private String filePath;
    private String mimeType;
    private int placeholderRes;
    private int targetSize = 0;

    public String getFilePath() {
        return filePath;
    }

    public ImageLoaderBuilder setFilePath(String filePath) {
        this.filePath = filePath;
        return this;
    }

    public String getMimeType() {
        return mimeType;
    }

    public ImageLoaderBuilder setMimeType(String mimeType) {
        this.mimeType = mimeType;
        return this;
    }

    public int getPlaceholderRes() {
        return placeholderRes;
    }

    public ImageLoaderBuilder setPlaceholderRes(int placeholderRes) {
        this.placeholderRes = placeholderRes;
        return this;
    }

    public int getTargetSize() {
        return targetSize;
    }

    public ImageLoaderBuilder setTargetSize(int targetSize) {
        this.targetSize = targetSize;
        return this;
    }


    /**
     * 设置图片加载后显示的大小
     *
     * @param size
     * @return
     */
    public ImageLoaderBuilder overrideSize(int size) {
        this.targetSize = size;
        return this;
    }

    /**
     * 设置图片加载完成前的placeHolder
     *
     * @param resId drawable/mipmap资源id
     * @return
     */
    public ImageLoaderBuilder placeHolder(@DrawableRes int resId) {
        this.placeholderRes = resId;
        return this;
    }


    /**
     * 设置加载后资源要展示的ImageView
     *
     * @param imageView ImageView
     */
    public void into(ImageView imageView) {
        imageViewHashMap.put(filePath, imageView);
        if (placeholderRes != 0) {
            imageView.setImageResource(placeholderRes);
        }
        ExecutorManager.get().post(new Runnable() {
            @Override
            public void run() {
                loadBitmapAndCache(mimeType, filePath);
                ImageView imageView = imageViewHashMap.get(filePath);
                if (imageView != null) {
                    imageView.post(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap bitmap = cachePool.get(filePath);
                            imageView.setImageBitmap(bitmap);
                        }
                    });
                }
            }
        });
    }


    private void loadBitmapAndCache(String mimeType, String filePath) {
        Bitmap bitmap = cachePool.get(filePath);
        if (bitmap != null && !bitmap.isRecycled()) {
            return;
        }

        // 解析视频帧bitmap
        if (MimeTypeUtil.isVideo(mimeType)) {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(filePath);
            Bitmap frame = retriever.getFrameAtTime();
            cachePool.put(filePath, frame);
            Log.d(TAG, "readAndResizeBitmap: key=" + filePath);
            return;
        }

        // 加载图片bitmap
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, opts);
        opts.inJustDecodeBounds = false;
        int originWidth = opts.outWidth;
        int originHeight = opts.outHeight;
        opts.inSampleSize = calcSampleSize(originWidth, originHeight);

        Bitmap resizeBitmap = BitmapFactory.decodeFile(filePath, opts);
        Log.d(TAG, "readAndResizeBitmap: key=" + filePath);
        cachePool.put(filePath, resizeBitmap);
    }

    private int calcSampleSize(int originWidth, int originHeight) {
        if (targetSize == 0) {
            return 1;
        }
        int ratio = 1;
        if (originWidth > targetSize || originHeight > targetSize) {
            int widthRatio = Math.round((float) originWidth / targetSize);
            int heightRatio = Math.round((float) originHeight / targetSize);
            ratio = Math.min(widthRatio, heightRatio);
        }
        return ratio;
    }


}
